<template>
  <div class="banner-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Banner管理</span>
          <el-button type="primary" @click="handleAdd">新增Banner</el-button>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column label="图片" width="180">
          <template #default="scope">
            <el-image 
              style="width: 100px; height: 60px" 
              :src="scope.row.imageUrl"
              :preview-src-list="[scope.row.imageUrl]"
              fit="cover"
            />
          </template>
        </el-table-column>
        <el-table-column prop="linkUrl" label="链接" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="120px">
        <!-- 图片上传 -->
        <el-form-item label="图片" required>
          <div class="upload-box">
            <el-upload
              class="upload-demo"
              action=""
              :http-request="uploadImage"
              :show-file-list="true"
              :file-list="imageList"
              list-type="picture-card"
              :on-remove="handleImageRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </div>
          <div class="upload-tip">支持jpg、png格式，单张不超过10M</div>
        </el-form-item>

        <el-form-item label="链接">
          <el-input v-model="form.linkUrl" />
        </el-form-item>
        <el-form-item label="开始时间" required>
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="选择开始时间"
          />
        </el-form-item>
        <el-form-item label="结束时间" required>
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="选择结束时间"
          />
        </el-form-item>
        <el-form-item label="排序">
          <el-input-number v-model="form.sort" :min="0" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getBannerList, addBanner, updateBanner, deleteBanner } from '@/api/banner'

const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const imageList = ref([])

const form = ref({
  id: undefined,
  imageUrl: '',
  linkUrl: '',
  startTime: '',
  endTime: '',
  sort: 0,
  status: 1
})

// 上传图片
const uploadImage = async (params: any) => {
  try {
    const formData = new FormData()
    formData.append('file', params.file)
    
    const res = await fetch('/api/common/upload', {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('token')
      },
      body: formData
    })
    
    const result = await res.json()
    if (result.code === 200) {
      imageList.value = [{
        name: params.file.name,
        url: result.url
      }]
      form.value.imageUrl = result.url
    } else {
      ElMessage.error(result.msg || '上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('上传失败')
  }
}

// 删除图片
const handleImageRemove = () => {
  imageList.value = []
  form.value.imageUrl = ''
}

// 获取banner列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getBannerList({
      pageCurrent: currentPage.value,
      pageSize: pageSize.value
    })
    tableData.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 新增banner
const handleAdd = () => {
  form.value = {
    id: undefined,
    imageUrl: '',
    linkUrl: '',
    startTime: '',
    endTime: '',
    sort: 0,
    status: 1
  }
  imageList.value = []
  dialogTitle.value = '新增Banner'
  dialogVisible.value = true
}

// 编辑banner
const handleEdit = (row: any) => {
  form.value = { ...row }
  if (row.imageUrl) {
    imageList.value = [{
      name: '已上传图片',
      url: row.imageUrl
    }]
  }
  dialogTitle.value = '编辑Banner'
  dialogVisible.value = true
}

// 删除banner
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该Banner吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteBanner(row.id)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      console.error(error)
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!form.value.imageUrl) {
    ElMessage.warning('请上传图片')
    return
  }
  if (!form.value.startTime) {
    ElMessage.warning('请选择开始时间')
    return
  }
  if (!form.value.endTime) {
    ElMessage.warning('请选择结束时间')
    return
  }

  try {
    if (form.value.id) {
      await updateBanner(form.value)
      ElMessage.success('更新成功')
    } else {
      await addBanner(form.value)
      ElMessage.success('新增成功')
    }
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error(error)
  }
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style scoped>
.banner-container {
  padding: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.upload-box {
  margin-bottom: 10px;
}
.upload-tip {
  font-size: 12px;
  color: #999;
}
</style> 